package cn.lazyturtle.bugpush.utils;
import com.aliyun.dingtalkoauth2_1_0.Client;
import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenResponse;
import com.aliyun.teaopenapi.models.*;
import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.Common;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.*;
import com.dingtalk.api.response.*;
import com.taobao.api.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import static cn.lazyturtle.bugpush.constant.ApiUrlConstant.*;

/**
 * @author admin
 * @date 2020/5/26 9:18
 */
@Component
@Slf4j
public class DingTalkUtils {
    @Value("${ding-talk.appKey}")
    private String appKey;
    @Value("${ding-talk.appSecret}")
    private String appSecret;
    @Value("${ding-talk.agentId}")
    private String agentId;

    public static Client createClient() throws Exception {
        Config config = new Config();
        config.protocol = "https";
        config.regionId = "central";
        return new Client(config);
    }

    /**
     * 获取token
     */
    public String getToken(){
        GetAccessTokenRequest getAccessTokenRequest = new GetAccessTokenRequest()
            .setAppKey(appKey)
            .setAppSecret(appSecret);
        try {
            Client client = DingTalkUtils.createClient();
            GetAccessTokenResponse accessToken = client.getAccessToken(getAccessTokenRequest);
            return accessToken.getBody().accessToken;
        } catch (TeaException err) {
            if (!Common.empty(err.code) && !Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
            }

        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!Common.empty(err.code) && !Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
            }

        }
        return null;
    }

    /**
     * 发送工作通知
     * @param token token
     * @param userIdList 接收者ID， 多个用','隔开
     * @param content   消息内容
     *
     */
    public boolean sendWorkNotify(String token, String userIdList,String title, String content,String msgUrl,
                                  String picUrl) {
        DingTalkClient client = new DefaultDingTalkClient(URL_SEND_WORK_MESSAGE);
        OapiMessageCorpconversationAsyncsendV2Request request = new OapiMessageCorpconversationAsyncsendV2Request();
        request.setAgentId(Long.parseLong(agentId));
        request.setUseridList(userIdList);
        request.setToAllUser(false);

        OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
        msg.setMsgtype("link");
        msg.setLink(new OapiMessageCorpconversationAsyncsendV2Request.Link());
        msg.getLink().setTitle(title);
        msg.getLink().setText(content);
        msg.getLink().setMessageUrl(msgUrl);
        msg.getLink().setPicUrl(picUrl);
        request.setMsg(msg);

        boolean bool = false;
        try {
            OapiMessageCorpconversationAsyncsendV2Response rsp = client.execute(request, token);
            log.info("发送消息:errCode:{}",rsp.getErrcode());
            if (rsp.getErrcode() == 0){
                bool = true;
            }
        } catch (ApiException e) {
            log.info("发送消息失败");
            e.printStackTrace();
        }
        return bool;
    }

    /**
     * 获取用户id。根据电话号
     * @param token token
     * @param mobile 手机号
     */
    public String getUserId(String token,String mobile){
        DingTalkClient client = new DefaultDingTalkClient(URL_GET_USER_ID_BY_PHONE);
        OapiUserGetByMobileRequest request = new OapiUserGetByMobileRequest();
        request.setMobile(mobile);
        try {
            OapiUserGetByMobileResponse execute = client.execute(request, token);
            if(execute.getErrcode() == 0){
                return execute.getUserid();
            }
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取用户信息
     * @param token token
     * @param userId 用户id
     */
    public String getUserInfo(String token, String userId){
        DingTalkClient client = new DefaultDingTalkClient(URL_GET_USER_INFO_BY_ID);
        OapiV2UserGetRequest req = new OapiV2UserGetRequest();
        req.setUserid(userId);
        req.setLanguage("zh_CN");
        OapiV2UserGetResponse rsp = null;
        try {
            rsp = client.execute(req, token);
            return rsp.getBody();
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return null;
    }
}
